# -*- coding: utf-8 -*-
"""
@Time : 2024/3/5 11:25 PM
@Author: imamhusan
@Des: 描述
"""
from fastapi import APIRouter, Security, Request
from core.Auth import verify_token
from core.Response import success, fail
from models.favor import Favor, ViewLog
from models.goods import Goods


router = APIRouter()


@router.post('/favor/{goods_id}', description='创建和获取收藏状态', dependencies=[Security(verify_token)])
async def add_or_get(req: Request, goods_id: int):
    try:
        user_id = req.state.user_id
        favor_obj, created = await Favor.get_or_create(user_id=user_id, goods_id=goods_id)
        if created:
            return success(data=favor_obj, msg='创建收藏记录')
        else:
            favor_obj.state = 0 if favor_obj.state else 1
            await favor_obj.save()
            return success(data=favor_obj, msg='收藏状态已改变')

    except Exception as e:
        return fail(str(e))


@router.get('/favor', description='获取用户收藏商品', dependencies=[Security(verify_token)])
async def get_favor(req: Request):
    try:
        lan = req.headers.get('lan', 'uy')
        user_id = req.state.user_id
        ids = await Favor.filter(user_id=user_id, state=1).order_by('update_time').values_list('goods_id', flat=True)
        goods_list = await Goods.filter(id__in=ids).values('id', 'image', 'price', 'views', 'quantity', f'title_{lan}')
        return success(data=goods_list, msg='获取收藏商品列表')

    except Exception as e:
        return fail(str(e))


@router.get('/view_log', description='观看商品列表', dependencies=[Security(verify_token)])
async def get_view_log(req: Request):
    try:
        lan = req.headers.get('lan', 'uy')
        user_id = req.state.user_id
        ids = await ViewLog.filter(user_id=user_id).limit(50).values_list('goods_id', flat=True)
        goods_list = await Goods.filter(id__in=ids).values('id', 'image', 'price', 'views', 'quantity', f'title_{lan}')
        return success(data=goods_list, msg='获取观看商品列表')
    except Exception as e:
        return fail(str(e))